package com.eascs.cloudFile.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.app.context.ConfigContext;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.cloudFile.entity.CloudDatalist;
import com.eascs.cloudFile.service.CloudFileService;
import com.eascs.common.dfs.fastdfs.FastDfsClient;
import com.eascs.common.exception.RuntimeIOException;
import com.eascs.common.ftp.FtpConfig;
import com.eascs.common.ftp.FtpHelper;
import com.eascs.common.http.HTTPResponse;
import com.eascs.common.http.HttpClients;
import com.eascs.common.util.EncodingUtil;
import com.eascs.common.util.StopWatch;
import com.eascs.file.form.FileForm;
import com.eascs.site.controller.BaseViewController;

@Controller
public class CloudAttachmentController extends BaseViewController {

	private final Logger logger = LoggerFactory.getLogger(CloudAttachmentController.class);

	@Reference
	private CloudFileService cloudFileService;
	@Autowired
	private FastDfsClient fastDfsClient;

	private HttpClients httpClients = new HttpClients();

	@Inject
	private FtpConfig ftpConfig;

	@RequestMapping("/attachment/cloidViewfile")
	public void downloadCloidAttachment(FileForm fileForm, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
		logger.debug("FileForm:[{}]", fileForm.toString());
		String datalistno = fileForm.getDatalistno().substring(0, fileForm.getDatalistno().lastIndexOf("."));
		CloudDatalist attachment = cloudFileService.queryDataListById(datalistno);
		if ("pdf".equals(attachment.getExtendName())) {
			httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + EncodingUtil.urlEncode(attachment.getOriginalName()));
			httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
		} else if (fastDfsClient.isImgPath(attachment.getExtendName())) {
			httpServletResponse.setContentType("image/" + attachment.getExtendName());
		} else {
			try {
				httpServletResponse.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(attachment.getOriginalName(), "utf-8"));
				httpServletResponse.setContentType("application/octet-stream; charset=utf-8");
			} catch (UnsupportedEncodingException e) {
				logger.error("UnsupportedEncodingException:[{}]", e.getMessage());
			}
		}
		cloidViewFile(fileForm, attachment, httpServletResponse, httpServletRequest);
		return;

	}

	private void cloidViewFile(FileForm fileForm, CloudDatalist attachment, HttpServletResponse httpServletResponse, HttpServletRequest request) {
		String filePath = attachment.getUrlPath();
		if (!fastDfsClient.isFastDfsPath(filePath)) {
			StopWatch watch = new StopWatch();
			try {
				ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
				FtpHelper.download(ftpConfig, byteArrayOutputStream, filePath);
				logger.debug("download from ftp, filePath={}, elapsedTime={},byteArrayOutputStream.size()={}", filePath, watch.elapsedTime(), byteArrayOutputStream.size());
				ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
				filePath = fastDfsClient.uploadInputStream(byteArrayInputStream, fastDfsClient.buildFastDfsPath(filePath, "grouploan", fileForm.getConvertType()), null);
				logger.info("FastDFS uploadPath:[{}]", filePath);
				attachment.setUrlPath(filePath);
				cloudFileService.updateUrlPath(attachment);
			} catch (Exception e) {
				logger.error("File FTP copy FastDFS error：[{}]", e.getMessage());
				throw new RuntimeIOException(e);
			} finally {
				logger.debug("upload to fastdfs, filePath={}, elapsedTime={}", filePath, watch.elapsedTime());
			}
		}
		if (null != filePath) {
			try {
				fastDfsClient.outputFile(httpServletResponse.getOutputStream(), filePath, fileForm.getConvertType());
				return;
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				throw new RuntimeIOException(e);
			}
		}
		// 以下代码无用，暂留
		filePath = ConfigContext.getStringValue("fastdfs.http_storage_server") + fastDfsClient.buildFastDfsPath(filePath, ConfigContext.getStringValue("fastdfs.group_name"), fileForm.getConvertType());
		logger.debug("forward to filePath={}", fastDfsClient.buildFastDfsPath(filePath, ConfigContext.getStringValue("fastdfs.group_name"), fileForm.getConvertType()));
		try {
			HTTPResponse response = httpClients.getAndResponse(filePath, null);
			byte[] bits = response.responseBinary();
			logger.info("img bits size[{}]", bits.length);
			httpServletResponse.getOutputStream().write(bits);
		} catch (IOException e) {
			throw new RuntimeIOException(e);
		}
	}

}
